package org.stars.dao.loader;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.stars.config.AppSettings;
import org.stars.config.Config;
import org.stars.config.MessageBundleImpl;
import org.stars.dao.config.DaoConfigImpl;

import static org.stars.config.Message.MESSAGES_LOAD;
import static org.stars.config.Message.SET_PARAMETER;

public class XmlConfigLoader extends XmlBaseLoader<DaoConfigImpl, DaoConfigImpl> {

	/**
	 * Name of the parameter put in AppSetting rapresenting the path of the config file (absolute)
	 */
	public final static String DAOSTARS_CONFIG_DIR="daostars_config_dir";
	
	public DaoConfigImpl load(String fileName) throws Exception
	{
		return load(fileName, DaoConfigImpl.class);
	}

	/* (non-Javadoc)
	 * @see org.stars.dao.loader.XmlLoader#load(java.lang.String, java.lang.Class)
	 */
	@Override
	protected DaoConfigImpl load(String fileName, Class<DaoConfigImpl> clazz)
			throws Exception {		
		Log log = LogFactory.getLog(getClass());
		
		String daostarsConfigDir="";
		if ((new File(fileName)).getParentFile()!=null)
		{
			daostarsConfigDir=(new File(fileName)).getParentFile().toString();
		}
		
		// load message i18n
		MessageBundleImpl bundle=new MessageBundleImpl();
		bundle.load();
		// before this line of code Message is not bind with bundle
		Config.setMessageBundle(bundle);
		
		log.info(MESSAGES_LOAD.with(bundle.getFileName(), bundle.getCurrentLocale().getDisplayName(),bundle.getCurrentLocale().toString()));
		
		// set dir of daostars's config file in parameter  DAOSTARS_CONFIG_DIR
		AppSettings.getInstance().setParameter(DAOSTARS_CONFIG_DIR, daostarsConfigDir);
		log.debug(SET_PARAMETER.with(DAOSTARS_CONFIG_DIR,daostarsConfigDir));
		
		// load daostars's config file
		DaoConfigImpl config=super.load(fileName, clazz);		
		Config.setDaoConfig(config);					
		
		// load macros
		config.setMacroMap(MacroLoader.load(config.getMacros()));
		
						
		//TODO: datasource
		//TODO: eventHandler
		//TODO: typeAliases
		config.setTypeAliasMap(TypeAliasLoader.load(config.getTypeAliases()));
		//TODO: typeHandler
		
		// load sqlMapperMap
		config.setSqlMapperMap(SourceLoader.load(config.getSources()));

						
		return config;
	}
			


}
